package com.wf.demo.sys.service;

import com.wf.demo.sys.dao.MenuDAO;
import com.wf.demo.sys.dao.RoleDAO;
import com.wf.demo.sys.dao.UserDAO;
import com.wf.demo.sys.pojo.Menu;
import com.wf.demo.sys.pojo.Role;
import com.wf.demo.sys.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: wf
 * @Date: 2019/12/19 20:21
 * @Description:
 */
@Service
public class UserService {

    @Autowired
    UserDAO userDAO;
    @Autowired
    RoleDAO roleDAO;
    @Autowired
    MenuDAO menuDAO;

    public List<User> list() {
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        return userDAO.findAll(sort);
    }
    public User get(long id) {
        return  userDAO.getOne(id);
    }
    public void delete(long id) {
        userDAO.delete(id);
    }
    public void update(User bean) {
        userDAO.save(bean);
    }
    public void add(User bean) {
        userDAO.save(bean);
    }
    public Boolean isExist(String userName){
        User user=userDAO.findByUsername(userName);
        return null!=user;
    }
    public boolean isExist(User bean) {
        //找到id
        long  id =bean.getId();
        //先得到对应id的对象在数据库的名字
        String oldName=userDAO.getOne(id).getUsername();
        String name=bean.getUsername();
        //如果名字没改变
        if (oldName.equals(name)){
            return false;
        }
      User  user= userDAO.findByUsername(name);
        return null!=user;
    }

    //根据userId查找所有的perms字符串
    public List<String> getAllPermsByid(Long userId) {
        User user = userDAO.findById(userId);
        Role role = user.getRole();
        List<Menu> menus = role.getMenuList();
        List<String> permsList = new ArrayList<>();
        for (Menu menu : menus) {
            //得到菜单里面所有的perms，有的是null，有的是sys:schedule:list,sys:schedule:info如此
            permsList.add(menu.getPerms());
        }
        return permsList;
    }
    public  User getByName(String name){
        return  userDAO.findByUsername(name);
    }

}